package com.base.vistter.iframe.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class UploadUtils {
    /**
     * 根据路径获取文件名字
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath){
        return filePath.substring(filePath.lastIndexOf("/") + 1 , filePath.lastIndexOf(".") + 1);
    }
    /**
     * 生成随机数
     *
     * @return
     */
    public static String getRandom() {
        Random random = new Random();
        return String.valueOf(random.nextInt(9999));
    }

    /**
     * 通过流生成icon图片
     * @param bufferedImage
     * @param toWidth
     * @param toHeight
     * @return
     */
    public static BufferedImage getScaledInstance(BufferedImage bufferedImage, int toWidth, int toHeight) {
        ImageIcon imageIcon = new ImageIcon(bufferedImage);
        BufferedImage newBufferedImage = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_4BYTE_ABGR);
        newBufferedImage.createGraphics().drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
        return newBufferedImage;
    }

    /**
     * BufferedImage 转换成 InputStream
     * @param bufferedImage
     * @return
     * @throws IOException
     */
    public static InputStream bufferedImageToInputStream(BufferedImage bufferedImage , String imageExt) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imageExt, os);
        return new ByteArrayInputStream(os.toByteArray());
    }

    public static InputStream bufferedImageToInputStream(BufferedImage bufferedImage) throws IOException {
        return bufferedImageToInputStream(bufferedImage , "png");
    }

    /**
     * 获取文件扩展名
     * @param filePath
     * @return
     */
    public static String getFileExt(String filePath){
        return filePath.substring(filePath.lastIndexOf(".") + 1);
    }
}
